package command.server;

import java.io.IOException;
import java.util.ArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import model.Conversation;
import model.MessageCommunication;
import model.User;
import server.ClientThread;
import server.Server;

public class AskTheConversationHistoryServer implements CommandServer {

    public AskTheConversationHistoryServer() {
    }

    @Override
    public void execute(ClientThread clientThread) {
        try {
            User u = (User) clientThread.getObjectInputStream().readObject();
            ArrayList<Conversation> conversations;
            if (u.isUserPrivileged()) {
                conversations = new ArrayList<>(Server.getServerConversationDAO().getConversationMap());
            } else {
                conversations = new ArrayList<>(Server.getServerConversationDAO().getConversationMap(u));
            }
            clientThread.getObjectOutputStream().writeObject(
                    new MessageCommunication(true, "asktheconversationhistoryclient"));
            clientThread.getObjectOutputStream().flush();
            clientThread.getObjectOutputStream().writeObject(conversations);
            clientThread.getObjectOutputStream().flush();
        } catch (IOException | ClassNotFoundException ex) {
            Logger.getLogger(AskTheConversationHistoryServer.class.getName()).log(Level.SEVERE,
                    "Fallo al ejecutar el comando de solicitud de historial de conversaciones en el servidor", ex);
        }
    }
}
